package com.appspot.battlerafts.servlets.game;

import com.appspot.battlerafts.classes.Game;
import com.appspot.battlerafts.enums.GameState;
import com.appspot.battlerafts.enums.MultiplayerEvents;
import com.appspot.battlerafts.jsons.StartGameJSON;
import com.appspot.battlerafts.utils.PMF;
import com.appspot.battlerafts.utils.Pusher;
import com.google.gson.Gson;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

import static com.appspot.battlerafts.utils.Util.returnSuccess;

/**
 * Created by IntelliJ IDEA.
 * User: Tonis
 * Date: 23.03.12
 * Time: 8:50
 * To change this template use File | Settings | File Templates.
 */

public class StartGame extends HttpServlet {

    private static final Logger log = Logger.getLogger(StartGame.class.getName());

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Gson gson = new Gson();
        String rawInput = request.getParameter("data");
        log.warning(rawInput);
        StartGameJSON start = gson.fromJson(rawInput, StartGameJSON.class);
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Game game;
        try {
            game = (Game) pm.getObjectById(Game.class, start.gameID);
            game.setGameState(GameState.RUNNING);
            game = pm.detachCopy(game);

        }finally {
            pm.close();
        }

        StartGameJSON startJSON = new StartGameJSON();

        startJSON.players = game.getItendedPlayers();
        startJSON.upgrades = start.upgrades;
        Pusher.triggerPush("presence-"+start.gameID, "client-"+MultiplayerEvents.STARTGAME.toString(), gson.toJson(startJSON));
        returnSuccess(response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
